package com.platform.controller;

import com.platform.annotation.SysOptionLog;
import com.platform.entity.OrderDetailEntity;
import com.platform.entity.OrderEntity;
import com.platform.entity.SysUserEntity;
import com.platform.entity.excel.OrderExcel;
import com.platform.service.OrderDetailService;
import com.platform.service.OrderService;
import com.platform.service.UserService;
import com.platform.util.OrderStatusEnum;
import com.platform.utils.*;
import com.platform.utils.excel.ExcelExport;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


/**订单管理:商城购买订单
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("order:list")
    public R list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);

        List<OrderEntity> orderList = orderService.queryList(query);
        int total = orderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());
//        for(OrderEntity orderEntity : orderList){
//            orderEntity.setRateValue(orderDetailService.queryRateValue(orderEntity.getOrderNo()));
//        }

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("order:info")
    public R info(@PathVariable("id") Integer id) {
        OrderEntity order = orderService.queryObject(id);
        order.setRateValue(orderDetailService.queryRateValue(order.getOrderNo()));
        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @SysOptionLog("添加商城订单")
    @RequiresPermissions("order:save")
    public R save_order(@RequestBody OrderEntity order) {
        orderService.save(order);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @SysOptionLog("修改商城订单")
    @RequiresPermissions("order:update")
    public R update_order(@RequestBody OrderEntity order) {
        orderService.update(order);


        return R.ok();
    }

    @RequestMapping("/export")
    @RequiresPermissions("order:export")
    public void code(
            @RequestParam(value = "orderNo", required = false) String orderNo,
            @RequestParam(value = "userPhone", required = false) String userPhone,
            @RequestParam(value = "payStatus", required = false) Integer payStatus,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "index", required = false) Integer index,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "payWay", required = false) Integer payWay,
            @RequestParam(value = "merchantId", required = false) Integer merchantId
            , HttpServletResponse response) throws IOException {
        int type = 1;
        List<OrderExcel> orderList = orderService.queryListExcel(orderNo, userPhone, payStatus, status, index, size, type, payWay, merchantId);

        ExcelExport ee = new ExcelExport("商城购买订单");
        String[] header = new String[]{"订单号", "用户编号", "商户名称", "手机号", "产品名称", "产品款式", "数量", "订单金额", "实付金额", "赠送能量", "释放SPC", "团队赠送SPC", "收货人", "收货人手机", "收货地址", "订单状态", "付款状态", "支付方式", "支付时间", "备注"};
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        for (OrderExcel orderExcel : orderList) {

            String orderno = orderExcel.getOrderNo(); //订单编号
            Long userId = orderExcel.getUserId(); //用户编号
            String merthanName = orderExcel.getMerchantName();//商户名称
            String userPhone1 = orderExcel.getUserPhone(); //用户手机
            String productname = orderExcel.getProductName(); //商品名称
            Integer number = orderExcel.getNumber(); //商品数量
            BigDecimal amount = orderExcel.getAmount();//订单金额
            BigDecimal realAmount = orderExcel.getRealAmount();//实付金额
            BigDecimal giveEnergy = orderExcel.getGiveEnergy();//赠送能量数量
            BigDecimal spcFree = orderExcel.getSpcFree();//释放spc数量
            BigDecimal giveTeam = orderExcel.getGiveTeam();//团队赠送spc
            String receiveUser = orderExcel.getReceiveUser();//收货人
            String receivePhone = orderExcel.getReceivePhone();//收货人手机号
            String province = orderExcel.getProvince();//省
            String city = orderExcel.getCity();//市
            String area = orderExcel.getArea();//区
            String address = orderExcel.getAddress();//具体地址
            String addressStr = province + city + area + address; //详细地址
            String statu = OrderStatusEnum.getDesc(orderExcel.getStatus());//订单状态
            String payStatu = orderExcel.getPayStatus() == 2 ? "已支付" : "未支付"; //支付方式
            String payWays = orderExcel.getPayWay() == 1 ? "微信" : "支付宝";//支付方式
            Date payDate = orderExcel.getPayDate();//支付时间
            String remark = orderExcel.getRemark();//备注


            if (StringUtils.isNotBlank(productname)) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("orderNo", orderno);
                map.put("userId", userId);
                map.put("userPhone", userPhone1);
                map.put("merchantName", merthanName);
                map.put("productName", productname);
                map.put("proStyle", "无");
                map.put("number", number);
                map.put("amount", amount);
                map.put("realAmount", realAmount);
                map.put("giveEnergy", giveEnergy);
                map.put("spcFree", spcFree);
                map.put("giveTeam", giveTeam);
                map.put("receiveUser", receiveUser);
                map.put("receivePhone", receivePhone);
                map.put("address", addressStr);
                map.put("status", statu);
                map.put("payStatus", payStatu);
                map.put("payWay", payWays);
                map.put("payDate", payDate);
                map.put("remark", remark);
                list.add(map);
            } else {
                Map m = new HashMap();
                m.put("orderno", orderno);
                List<OrderDetailEntity> orderDetailEntityList = orderDetailService.queryList(m);
                for (OrderDetailEntity orderDetailEntity : orderDetailEntityList) {
                    LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                    map.put("orderNo", orderDetailEntity.getOrderNo());
                    map.put("userId", userId);
                    map.put("merchantName", merthanName);
                    map.put("userPhone", userPhone1);
                    map.put("productName", orderDetailEntity.getProName());
                    map.put("proStyle", orderDetailEntity.getStyleName());
                    map.put("number", orderDetailEntity.getNum());
                    map.put("amount", amount);
                    map.put("realAmount", realAmount);
                    map.put("giveEnergy", giveEnergy);
                    map.put("spcFree", spcFree);
                    map.put("giveTeam", giveTeam);
                    map.put("receiveUser", receiveUser);
                    map.put("receivePhone", receivePhone);
                    map.put("address", addressStr);
                    map.put("status", statu);
                    map.put("payStatus", payStatu);
                    map.put("payWay", payWays);
                    map.put("payDate", payDate);
                    map.put("remark", remark);
                    list.add(map);
                }
            }
        }
        ee.addSheetByMap("商城购买订单", list, header);
        ee.export(response);
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
//@SysOptionLog("删除商城订单")
    @RequiresPermissions("order:delete")
    public R delete_order(@RequestBody Integer[] ids) {
        orderService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<OrderEntity> list = orderService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {
        int sum = orderService.queryTotal(params);

        return R.ok().put("sum", sum);
    }

//    /**
//     * 确定收货
//     *
//     * @param id
//     * @return
//     */
//    @RequestMapping("/confirm")
//    @RequiresPermissions("order:confirm")
//    public R confirm(@RequestBody Integer id) {
//        orderService.confirm(id);
//
//        return R.ok();
//    }

    /**
     * 发货
     *
     * @param order
     * @return
     */
    @RequestMapping("/send")
    @RequiresPermissions("order:sendGoods")
    public R sendGoods(@RequestBody OrderEntity order) {
        int status = orderService.sendGoods(order);
        AliSmsUtil.sendSms(order.getUserPhone(), "SMS_165411956", "", order.getLogisticsno());
        return R.ok();
    }
}